﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Dict.DataModel;
using Dict.Blo;

namespace UI
{
    public class UIYggdrasil : Page
    {
        public UILabel totalSeed;
        public UILabel currUsed;
        public UILabel currLevel;
        string strCurrUsed;
        string strCurrLv;

        public List<GameObject> items;
        public List<Transform> anthors;//测试
        public List<UILabel> texts;
        public List<TweenAlpha> alphas;
        public List<GameObject> lights;
        public UIButton levelupBtn;

        public GameObject innerPanel;

        public UILabel maxGroupTip;

        //模版
        public GameObject template;

        #region 数据
        int currSeedId;
        public bool maxLevel;
        TableWorldSeed nextLevelSeed;
        List<TableWorldSeed> worldSeeds;
        List<int> opens;
        public int nextSeedUsed;
        public int totalSeedHas;
        #endregion
        //worldtree_level_up_tip_text_2

        public UIYggdrasilAnimation anim;

        public GameObject effect0;
        public List<GameObject> effects;
        public bool firstOpen = true;

        protected override void DoOpen()
        {
            firstOpen = true;
            Init();
            anim.In();
            GetComponent<UIYggdrasilEvent>().timeline = 1.5f;
            
           // AudioManager.Instance.PlayUIAudioChannel("silica_com_0006");

            onWorldSeedUpdate += StaticData.funcNavKit.OnWorldSeedUpdate;
        }

        protected override void DoClose()
        {
            onWorldSeedUpdate -= StaticData.funcNavKit.OnWorldSeedUpdate;
        }

        void Awake()
        {
            strCurrUsed = TableTextBlo.GetText("world_seed_x");
            strCurrLv = TableTextBlo.GetText("current_level");
        }

        public void Reflush()
        {
            if (StaticData.playerData.CurrentWorldSeedLevel % 5 == 0)
            {
                GetComponent<UIYggdrasilEvent>().timeline = 3.5f;
                InitData(false);
            }
            else
            {
                Init();
                GetComponent<UIYggdrasilEvent>().timeline = 1.5f;
            }
            firstOpen = false;
        }

        void Init()
        {
            InitData();
        }

        protected void InitData(bool isCur = true)
        {
            if (isCur)
            {
                this.worldSeeds = StaticData.playerData.worldSeed.GetCurrentGroupSeed(out maxLevel);
                currSeedId = StaticData.playerData.CurrentWorldSeedLevel;

            }
            else
            {
                this.worldSeeds = StaticData.playerData.worldSeed.GetPreviewGroupSeed();
                currSeedId = StaticData.playerData.CurrentWorldSeedLevel - 1;
                maxLevel = false;
                if (currSeedId == 84) maxLevel = true;
            }

            this.worldSeeds.Sort((lh, rh) => { return int.Parse(lh.id) - int.Parse(rh.id); });
            opens = new List<int>();

            foreach (var seed in worldSeeds)
            {
                opens.Add(int.Parse(seed.id) <= currSeedId ? 2 : int.Parse(seed.id) == currSeedId + 1 ? 1 : 0);
            }

            if (!maxLevel)
            {
                nextLevelSeed = TableWorldSeedBlo.GetWorldSeedById((currSeedId + 1).ToString());
                //世界之树数字
                var costs = nextLevelSeed.cost.Split(new char[1] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);

                var costId = costs[0];

                totalSeedHas = (int)StaticData.playerData.GetSimpleItemCount(costId);
                nextSeedUsed = int.Parse(costs[1]);
            }
            else
            {
                var currLevelSeed = TableWorldSeedBlo.GetWorldSeedById((currSeedId).ToString());
                var costs = currLevelSeed.cost.Split(new char[1] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);

                var costId = costs[0];

                totalSeedHas = (int)StaticData.playerData.GetSimpleItemCount(costId);
                nextSeedUsed = 0;

                nextLevelSeed = null;
            }

#if UNITY_EDITOR
            Debug.Log("[DEBUG] Yggdrasil => current id:" + currSeedId + "");
            foreach (var seed in worldSeeds)
            {
                Debug.Log("[DEBUG] Yggdrasil => world seed id:" + seed.id);
            }
            if (nextLevelSeed != null)
            {
                Debug.Log("[DEBUG] Yggdrasil => next id:" + nextLevelSeed.id + "");
            }
#endif

            if (!isCur)
            {
                for (int i = 0; i < 5; i++) opens[i] = 2;
            }

            InitUI();
            if (!isCur)
            {
                StartCoroutine(_ShowNextGroup());
            }

        }

        protected void InitUI()
        {
            //五个3D球球
            int index = 0;
            foreach (var open in opens)
            {
                var seed = worldSeeds[index];

                var script = GetGameObject(index).GetComponent<UIYggdrasilIcon>();
                script.Init(seed, (IconType)open, index, this);

                index++;
            }

            //四个箭头
            foreach (var light in lights) light.SetActive(false);

            index = 0;
            foreach (var open in opens)
            {
                if (open != 2) break;

                if (index++ == 0) continue;

                lights[index - 2].SetActive(true);

            }

            //UI
            totalSeed.text = totalSeedHas.ToString();
            currUsed.text = string.Format(strCurrUsed, nextSeedUsed);
            currLevel.text = string.Format(strCurrLv, StaticData.playerData.CurrentWorldSeedLevel);

            //PopupText
            index = 0;
            foreach (var seed in worldSeeds)
            {
                var strs = seed.get.Split(new char[1] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
                if (seed.type == 1)
                {
                    texts[index++].text = TableTextBlo.GetText(seed.desc) + "[53ed4b]+" + strs[1] + "[-]";
                }
                else if (seed.type == 2)
                {
                    texts[index++].text = "[d566f5]" + TableTextBlo.GetText(seed.desc) + "[-]";// + "[d566f5]" + strs[0] +" " + strs[1] + "[-]";
                }
                else if (seed.type == 3)
                {
                    texts[index++].text = "[d566f5]" + TableTextBlo.GetText(seed.desc) + "[-]";
                }
            }

            var lastSeed = Dict.Blo.TableWorldSeedBlo.GetNextRoleLevelup(StaticData.playerData.CurrentWorldSeedLevel);
            var str = TableTextBlo.GetText("worldtree_level_up_tip_text_" + lastSeed.type);
            maxGroupTip.text = string.Format(str, lastSeed.id, "[d566f5]" + TableTextBlo.GetText(lastSeed.desc) + "[-]");
        }


        GameObject GetGameObject(int authorIndex)
        {
            anthors[authorIndex].DestroyChildren();

            GameObject obj = GameObject.Instantiate(template);
            obj.transform.SetParent(anthors[authorIndex]);
            obj.transform.localScale = Vector3.one;
            obj.transform.localPosition = Vector3.zero;
            obj.SetActive(true);

            return obj;
        }

        public void ShowPopupText(int index)
        {
            var alpha = alphas[index];
            alpha.ResetToBeginning();
            alpha.PlayForward();
        }


        public void OpenInnerPanel()
        {
            innerPanel.SetActive(true);
            innerPanel.GetComponent<UIYggdrasilInner>().Init();
        }

        public void ClosedInnerPanel()
        {
            innerPanel.SetActive(false);
        }

        public void PlayEffect()
        {
            int currIndex = 0;
            foreach (var seed in worldSeeds)
            {
                if (int.Parse(seed.id) == StaticData.playerData.CurrentWorldSeedLevel + 1)
                {
                    break;
                }
                currIndex++;
            }

            StartCoroutine(_DelayPlayEffect(currIndex));

            if (currIndex > 0)
            {
                GameObject inst1 = GameObject.Instantiate(effects[currIndex - 1]);
                inst1.SetActive(true);
                inst1.transform.SetParent(effects[currIndex - 1].transform);
                inst1.transform.localScale = Vector3.one;
                inst1.transform.localPosition = Vector3.zero;
                inst1.transform.SetParent(effects[currIndex - 1].transform.parent);
                Destroy(inst1, 5f);
            }
        }

        IEnumerator _DelayPlayEffect(int index)
        {
            if (index != 0)
            {
                AudioManager.Instance.PlayUIAudioChannel("qiannengjiefang");
                yield return new WaitForSeconds(1.5f);
            }
            else
            {
                AudioManager.Instance.PlayUIAudioChannel("qiannengjiefang2");
            }
            GameObject inst0 = GameObject.Instantiate(effect0);
            inst0.SetActive(true);
            inst0.transform.SetParent(anthors[index]);
            inst0.transform.localScale = Vector3.one;
            inst0.transform.localPosition = Vector3.zero;
            inst0.transform.SetParent(anthors[index].parent);
            Destroy(inst0, 1.5f);
        }

        IEnumerator _ShowNextGroup()
        {
            yield return new WaitForSeconds(2f);
            anim.SwitchGroup();
            yield return new WaitForSeconds(1f);
            Init();
        }

        #region OnWorldSeedUpdate
        public delegate void OnWorldSeedUpdate(int cur, int need);
        public OnWorldSeedUpdate onWorldSeedUpdate;
        #endregion
    }
}